package com.zg.paging3.activity.net

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import com.zg.ktcomwan.model.ArticleBean
import com.zg.paging3.activity.net.data.RetrofitUtils
import retrofit2.HttpException
import java.io.IOException

/***
 * @Author:      zxd
 * @CreateDate:  2021/7/9 14:21
 * @Description: 测试向的api，等稳定版再说
 * https://www.codenong.com/cs110213744/
 * https://blog.csdn.net/u012591761/article/details/110213744
 * https://blog.csdn.net/weixin_42046829/article/details/110140424
 */
@ExperimentalPagingApi
class NetDataRemoteMediator() : RemoteMediator<Int, ArticleBean>() {

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, ArticleBean>
    ): MediatorResult {
        return return try {

            /**
             * 在这个方法内将会做三件事
             *
             * 1. 参数 LoadType 有个三个值，关于这三个值如何进行判断
             *      LoadType.REFRESH
             *      LoadType.PREPEND
             *      LoadType.APPEND
             *
             * 2. 访问网络数据
             *
             * 3. 将网路插入到本地数据库中
             */

            var pageCount = Int.MAX_VALUE
            var curPage = 0

            // 第一步： 判断 LoadType
            val pageKey = when (loadType) {
                // 首次访问 或者调用 PagingDataAdapter.refresh()
                LoadType.REFRESH -> null

                // 在当前加载的数据集的开头加载数据时
                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)

                // 上拉加载更多时触发
//                LoadType.APPEND -> return if (curPage == 0) MediatorResult.Success(
//                    endOfPaginationReached = false
//                ) else curPage + 1

                LoadType.APPEND -> {
                    val lastItem = state.lastItemOrNull()
                        ?: return MediatorResult.Success(
                            endOfPaginationReached = true
                        )
                    lastItem.id
                }
            }

            // 第二步： 请问网络分页数据
            val page = /*pageKey ?:*/ 0
            //获取网络数据

            val result = RetrofitUtils.service.getHomeArticleList(page)
            curPage = result.data.curPage
            pageCount = result.data.pageCount
            val data = result.data.datas
            val endOfPaginationReached = data.isEmpty()

            // 第三步： 插入数据库
            /*val userDao = db.userDao()
            if (!endOfPaginationReached) {
                userDao.insertUsers(data)
            }*/
            return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
        } catch (e: IOException) {
            return MediatorResult.Error(e)
        } catch (e: HttpException) {
            return MediatorResult.Error(e)
        }
    }
}